﻿using AutoMapper;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using WMS.FC.Domain.DomainObject.System;
using WMS.FC.Domain.DomainObject.Technology;
using WMS.FC.Domain.PersistenceObject.Business;
using WMS.FC.Domain.Repository;
using WMS.FC.Domain.Service.System;
using WMS.FC.Domain.Service.Technology.Interface;

namespace WMS.FC.Domain.Service.Technology
{
    public class AddTechnologyRouteService : ServiceBase, IAddTechnologyRouteService
    {
        protected readonly ITechnologyRepository technologyRepository;

        public AddTechnologyRouteService(
            ILogger<ServiceBase> logger,
            IOptions<WmsSettings> options,
            IMapper mapper,
            ITechnologyRepository technologyRepository)
            : base(logger, options, mapper)
        {
            this.technologyRepository = technologyRepository;
        }

        public async Task<ActionResultBase> AddTechnologyRoute(TechnologyRouteDO? dO, UserInfo userInfo)
        {
            var result = new ActionResultBase("新增工艺路径");
            try
            {
                if (dO == null)
                    return result.ArgumentError("工艺路径数据不能为空");

                var count = await technologyRepository.GetCount<TechnologyRoutePO>(entity => entity.Code == dO.Code);
                if (count > 0)
                    return result.BusinessError($"编码:{dO.Code},工艺路径已经存在");

                var technologyRoutePO = mapper.Map<TechnologyRoutePO>(dO);
                technologyRoutePO.WarehouseCode = options.Value.WarehouseCode;
                technologyRoutePO.SortNumber = await technologyRepository.GetMaxTechnologyRouteSortNumber() + 1;
                count = await technologyRepository.Insert(technologyRoutePO, userInfo);
                if (count == 0)
                    return result.DbError("新增工艺路径异常");

                result.Message = "新增数据成功";
            }
            catch (Exception ex)
            {
                return result.Exception(ex);
            }

            return result;
        }
    }
}
